package com.mrzhou.gateway.filter;

import com.mrzhou.core.tool.utils.JacksonUtil;
import com.mrzhou.core.tool.utils.JwtUtil;
import com.mrzhou.core.tool.utils.StringUtil;
import com.mrzhou.gateway.props.AuthProperties;
import com.mrzhou.gateway.provider.AuthProvider;
import com.mrzhou.gateway.provider.RequestProvider;
import com.mrzhou.gateway.provider.ResponseProvider;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取当前的url
        String originURL = RequestProvider.getOriginRequestUrl(exchange);
        String path = request.getURI().getPath();
        if(isSkip(originURL) || isSkip(path)) {
            return chain.filter(exchange);
        }
        String headerToken =request.getHeaders().getFirst(AuthProvider.TOKEN_HEADER);
        if(!StringUtil.isNotBlank(headerToken)) {
            return unAuth(response, "缺失令牌, 鉴权失败！");
        }
        String token = JwtUtil.getToken(headerToken);
        Claims claims = JwtUtil.parseJwt(token);
        if(null ==claims) {
            return unAuth( response,"请求未授权！");
        }

        return chain.filter(exchange);
    }

    private boolean isSkip(String path) {
        return AuthProvider.defaultSkip().stream().map(url -> url.replace(AuthProvider.TARGET, AuthProvider.REPLACEMENT)).anyMatch(path::startsWith) ||
                authProperties.getSkipUrl().stream().map(url -> url.replace(AuthProvider.TARGET, AuthProvider.REPLACEMENT)).anyMatch(path::startsWith);
    }

    private Mono<Void> unAuth(ServerHttpResponse resp, String msg) {
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = JacksonUtil.toJsonString(ResponseProvider.unAuth(msg));
        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -1000;
    }
}
